루비는 메서드 정의를 고정된 서명에서 동적 인터페이스로 발전시킵니다. 스플랫 연산자와 표현식 기반 로직을 익히면, 복잡한 오버로딩 없이도 다양한 데이터 밀도에 자연스럽게 대응하는 메서드를 만들 수 있습니다.
1. 지능형 기본값과 스플랫
루비는 매개변수를 서명 내에서 초기화할 수 있게 해주며, 최소한의 데이터로도 기능을 보장합니다. 스플랫 연산자 (*) 은 다리 역할을 합니다: 매개변수에서는 추가 인자를 배열로 수집하고, 호출 시에는 배열을 개별 슬롯으로 '해체'합니다.
2. 표현식 기반 반환
루비 메서드는 자동으로 마지막으로 실행된 표현식의 값을 반환합니다. 그러나 return 키워드는 조기에 종료하거나 여러 값을 배열로 반환하여 병렬 할당을 위해 전략적으로 사용됩니다.
num, sq = meth_three
# 루비는 (num, sq)를 배열 [32, 1024]로 패키징합니다
# 루비는 (num, sq)를 배열 [32, 1024]로 패키징합니다
main.py
TERMINALbash — 80x24
> Ready. Click "Run" to execute.
>
QUESTION 1
What is the primary role of the asterisk (*) in a method parameter list?
To mark a variable as a pointer to a memory address.
To capture a variable number of arguments into a single array.
To multiply the incoming argument by its index.
To indicate the method is private.
✅ Correct!
In a signature, `*` bundles all 'extra' arguments into an array named after the parameter.❌ Incorrect
In Ruby, `*` in parameters is the 'splat' operator used for variable-length argument lists.QUESTION 2
Given `def show(x, y=10)`, what happens if you call `show(5)`?
An ArgumentError is raised because two arguments are required.
x becomes 5 and y becomes 10.
x becomes 5 and y becomes nil.
The method returns 15 automatically.
✅ Correct!
Since y has a default value of 10, the method proceeds using that default when the second argument is omitted.❌ Incorrect
Default values allow methods to be functional even when the caller provides minimal data.QUESTION 3
What does 'Array Expansion' (Exploding) refer to in a method call?
Converting a string into an array of characters.
Deleting all elements in an array to free memory.
Using `*` before an array to pass its elements as individual arguments.
Expanding the heap to accommodate larger arrays.
✅ Correct!
Using `*arr` in a call 'explodes' the array, filling the method's parameter slots one by one.❌ Incorrect
Expansion refers to satisfying individual parameters using the contents of a single array.QUESTION 4
If a Ruby method has no explicit `return` keyword, what does it return?
It returns nil by default.
It returns true if the code executed successfully.
It returns the value of the last expression evaluated.
It returns the name of the method as a string.
✅ Correct!
Ruby is expression-based; the result of the final line is the implicit return value.❌ Incorrect
Unless interrupted by an explicit `return`, Ruby always passes back the result of the last expression.QUESTION 5
How are multiple return values handled in `return a, b`?
Ruby only returns the first value (a).
Ruby returns an array `[a, b]` which can be destructured.
It results in a syntax error; only one value can be returned.
The values are added together before returning.
✅ Correct!
Ruby packages multiple values into an array, allowing for clean parallel assignment like `x, y = meth()`.❌ Incorrect
Multiple values are conveniently bundled into an array for the caller.Flexible Logging System Case Study
Designing an adaptive interface
You are building a logging system. Usually, you only pass a message. Occasionally, you need to pass a list of error codes. You define the method: `def log(msg='Info', *codes)`. The codes should be joined into a string if present.
Q
If you call `log()`, what are the values of `msg` and `codes` inside the method?
Solution:
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
`msg` will be 'Info' (the default value) and `codes` will be an empty array `[]`.
Q
If you have an array `errs = [404, 500]`, how do you call `log` so 'Critical' is the message and the errors are captured in the `codes` array?
Solution:
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Call it using the splat operator: `log('Critical', *errs)`. This explodes the array into individual arguments after the first one.
Q
How does Ruby's expression-based return benefit this logger if the last line is `codes.empty? ? msg : "#{msg}: #{codes.join(', ')}"`?
Solution:
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.
The method automatically returns the formatted string without needing an explicit `return` keyword, making the code more concise and readable.